<?php

// Check that test is not FALSE; otherwise, show user an error.
function assert_($test)
{
	if ($test === FALSE)
	{
		echo '<html><head><title>Proxy</title></head><body><h1>Fatal Error</h1></body></html>';
		exit(1);
	}
}

// Patch this version of PHP with curl_setopt_array as needed.
if (!function_exists('curl_setopt_array')) {
	function curl_setopt_array($ch, $curl_options)
	{
		foreach ($curl_options as $option => $value) {
			if (!curl_setopt($ch, $option, $value)) {
				return FALSE;
			}
		}
		return TRUE;
	}
}

// Fetch the URL by logging into proxy with credentials.
function fetch($url, $proxy, $port, $user, $pwd)
{
	$ch = curl_init($url);
	assert_($ch);
	$options = array(
		CURLOPT_PROXY => $proxy . ':' . $port,
		CURLOPT_PROXYAUTH => CURLAUTH_NTLM,
		CURLOPT_PROXYUSERPWD => $user . ':' . $pwd,
		CURLOPT_RETURNTRANSFER => TRUE
	);
	assert_(curl_setopt_array($ch, $options));
	$transfer = curl_exec($ch);
	curl_close($ch);
	assert_($transfer);
	return $transfer;
}

// Run path with stdin and return program's status code.
function order($path, $stdin, &$stdout, &$stderr)
{
	$cmd = './' . basename($path);
	$descriptorspec = array(
		array('pipe', 'r'),
		array('pipe', 'w'),
		array('pipe', 'w')
	);
	$cwd = dirname($path);
	$process = proc_open($cmd, $descriptorspec, $pipes, $cwd, $_REQUEST);
	assert_($process);
	for ($total = 0; $total < strlen($stdin); $total += $written)
	{
		$written = fwrite($pipes[0], substr($stdin, $total));
		assert_($written);
	}
	assert_(fclose($pipes[0]));
	$stdout = stream_get_contents($pipes[1]);
	assert_($stdout);
	assert_(fclose($pipes[1]));
	$stderr = stream_get_contents($pipes[2]);
	assert_($stderr);
	assert_(fclose($pipes[2]));
	return proc_close($process);
}

function main()
{
	// Collect information to run over the proxy.
	@ $user = $_REQUEST['user'];
	@ $pwd = $_REQUEST['pwd'];

	// Fetch the URL and process it with the backend.
	$transfer = fetch('http://rssblog.whatisrss.com/feed/', 'labproxy.pcci.edu', 8080, $user, $pwd);
	$status = order('/home/Chappell_Stephen/public_html/backend.py', $transfer, $stdout, $stderr);

	// Check for errors and display the final output.
	assert_(strlen($stderr) == 0);
	echo $stdout;
}

if (!debug_backtrace())
{
	//main();
	order('cmd dir', '', $stdout, $stderr);
	echo $stdout;
}

?>
